﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using DevDefined.OAuth.Consumer;
using DevDefined.OAuth.Framework;
namespace AbstractLabs.PowerShell.Twitter
{
    [Cmdlet(VerbsCommon.Set, "Tweet")]
    public class TweetCmdlet : Cmdlet
    {
        [Parameter(Mandatory = true)]
        public string Message { get; set; }

        protected override void BeginProcessing()
        {
            base.BeginProcessing();
            bool expect100Continue = System.Net.ServicePointManager.Expect100Continue;
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;
                OAuthConsumerContext context = new OAuthConsumerContext();
                context.ConsumerKey = Properties.Settings.Default.ConsumerKey;
                context.ConsumerSecret = Properties.Settings.Default.ConsumerSecret;
                context.SignatureMethod = SignatureMethod.HmacSha1;
                OAuthSession session = new OAuthSession(context, (Uri)null, (Uri)null, (Uri)null);
                IConsumerRequest request = session.Request(Properties.Settings.Default.Token);
                request.Context.Headers.Remove("Expect");
                request.Context.RequestMethod = "POST";
                UriBuilder builder = new UriBuilder(Uri.UriSchemeHttp, "api.twitter.com");
                builder.Path = String.Concat("/", Properties.Settings.Default.ApiVersion, "/statuses/update.xml");
                builder.Query = String.Concat("status=", Uri.EscapeDataString(Message));
                request.Context.RawUri = builder.Uri;
                WriteVerbose(request.ReadBody());
            }
            catch (Exception exception)
            {
                WriteError(new ErrorRecord(exception, String.Empty, ErrorCategory.WriteError, null));
            }
            finally
            {
                System.Net.ServicePointManager.Expect100Continue = expect100Continue;
            }


        }
    }

}
